﻿using Net.Server;
using Net.Share;
using Net.System;

namespace WordGames.Service
{
    public class CentralServer : TcpServer<Node>
    {
        private readonly Dictionary<string, List<HostConfig>> _serviceRegistry = [];

        protected override void OnStartupCompleted()
        {
            base.OnStartupCompleted();
            OnNetworkDataTraffic += (df) =>
            {
                Console.Title = $"Central {Port} {df}";
            };
        }

        protected override void OnReceiveDataHandler(Node client, IRpcModel model, ISegment segment)
        {
            switch ((ProtoType)model.Protocol)
            {
                case ProtoType.RegisterDiscovery:
                    {
                        lock (this) 
                        {
                            var name = model.AsString;
                            var host = model.As<HostConfig>();
                            if (!_serviceRegistry.TryGetValue(name, out var hosts))
                                _serviceRegistry.Add(name, hosts = []);
                            hosts.Add(host);
                            Multicast([.. Clients.Values], ProtoType.ConnectDiscoveryServer, _serviceRegistry);
                        }
                    }
                    break;
            }
        }
    }
}